package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.redis.JobRedisKey;
import cn.wolfcode.web.feign.SeckillProductFeignApi;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
@Data
public class InitSeckillProductJob implements SimpleJob {
    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${jobCron.userCache}")
    private String cron;
//    任务内容
    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println("当前线程"+Thread.currentThread()+",当前分片参数:"+shardingContext.getShardingParameter());
        String time = shardingContext.getShardingParameter();
//        远程调用秒杀服务获取秒杀列表集合
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.queryByTimeForJob(Integer.valueOf(time));
        if(Objects.isNull(result)||result.hasError()){
//            通知管理员
            System.out.println("远程调用出错啦");
            return;
        }
        List<SeckillProductVo> seckillProductVoList = result.getData();
//        删除之前的数据
        String key = JobRedisKey.SECKILL_PRODUCT_HASH.getRealKey(time);
        String seckillStockCountlKey = JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time);
        redisTemplate.delete(key);
        redisTemplate.delete(seckillStockCountlKey);
//        重新存储数据
        for (SeckillProductVo seckillProductVo : seckillProductVoList) {
//                  存储商品整体数据
                redisTemplate.opsForHash().put(key,
                        String.valueOf(seckillProductVo.getId()),
                        JSON.toJSONString(seckillProductVo));
//                存储还有多少库存
                redisTemplate.opsForHash().put(seckillStockCountlKey,String.valueOf(seckillProductVo.getId()),String.valueOf(seckillProductVo.getStockCount()));
        }
    }
}
